package com.ja.util;

import java.util.ArrayList;
import java.util.List;
/**
 * <style>*{font-size: 14px;font-weight: bold;}div{height:28px;}img {position: fixed;bottom: 10px;right: 10px;height: 50px;}span{border: 3px solid blue;color: white;background: blue;display: inline-block;box-shadow: 2px 2px gray;margin: 2px 10px;margin-left: 40px;}l div{font-size:40px;display: inline-block;line-height: 16px;position: absolute;margin-top: -3px;font-weight: lighter;color: red;}p{font-weight: lighter;}l{display: inline-block;width: 80px;text-align: right;color: black;margin-top:10px;}</style><img src="https://a3.qpic.cn/psb?/V13i62Dj12ePbQ/NZmahM6aAmswZqIzVUkRHAvJMKUvnBP*ccASpf*fwec!/m/dF4BAAAAAAAAnull&bo=zwGhAAAAAAADB00!&rf=photolist&t=5"></img><div class="me" style="margin-top:-26px;">
 * <p>Desc：<!--TODO-->JAVA文件
 * </p><l>INFO<div>☞</div></l><span>文件名：RedPacketUtil.java　　　版本：v1.0
 * </span><br><l>Date<div>☞</div></l><span>2018年3月20日 下午4:39:08
 * </span><br><l>Author<div>☞</div></l><span>Bean
 * </span></div>
 */
public class RedPacketUtil {
	private static final int MINMONEY = 1;// 最小红包额度
	private static final int MAXMONEY = 200000 * 10;// 最大红包额度
	private static final double TIMES = 2.1;// 每个红包最大是平均值的倍数
	/**
	 * 拆分红包
	 * money = 红包金额*100
	 */
	public static List<Integer> splitRedPackets(int money, int count) {
		if (!isRight(money, count)) {
			return null;
		}
		List<Integer> list = new ArrayList<Integer>();
		int max = (int) (money * TIMES / count);// 红包最大金额为平均金额的TIMES倍
		max = max > MAXMONEY ? MAXMONEY : max;
		for (int i = 0; i < count; i++) {
			int one = random(money, MINMONEY, max, count - i);
			list.add(one);
			money -= one;
		}
		return list;
	}

	/**
	 * 随机红包额度
	 */
	private static int random(int money, int minS, int maxS, int count) {
		if (count == 1) return money;// 红包数量为1，直接返回金额
		if (minS == maxS) return minS;// 如果最大金额和最小金额相等，直接返回金额
		int max = maxS > money ? money : maxS;
		int one = ((int) Math.rint(Math.random() * (max - minS) + minS)) % max + 1;// 随机产生一个红包
		int money1 = money - one;
		// 判断该种分配方案是否正确
		if (isRight(money1, count - 1)) {
			return one;
		} else {
			double avg = money1 / (count - 1);
			if (avg < MINMONEY) return random(money, minS, one, count);// 递归调用，修改红包最大金额
			else if (avg > MAXMONEY) return random(money, one, maxS, count);// 递归调用，修改红包最小金额
		}
		return one;
	}

	/**
	 * 判断红包是否合法
	 */
	private static boolean isRight(int money, int count) {
		double avg = money / count;
		if (avg < MINMONEY) return false;
		if (avg > MAXMONEY) return false;
		return true;
	}

	public static void main(String[] args) {
		System.out.println(splitRedPackets((int) (1*10), 4));
	}
}